package org.fjsei.yewu.aop;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.graphql.server.WebGraphQlInterceptor;
import org.springframework.graphql.server.WebGraphQlRequest;
import org.springframework.graphql.server.WebGraphQlResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.Map;

@Component
public class GraphQLLoggingInterceptor implements WebGraphQlInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(GraphQLLoggingInterceptor.class);
    private final DatabaseClusterMonitor clusterMonitor;

    public GraphQLLoggingInterceptor(DatabaseClusterMonitor clusterMonitor) {
        this.clusterMonitor = clusterMonitor;
    }

    @Override
    public Mono<WebGraphQlResponse> intercept(WebGraphQlRequest request, Chain chain) {
        // 检查服务是否可用
        if (!clusterMonitor.isServiceEnabled()) {
            logger.warn("Rejecting GraphQL request due to maintenance mode: {}", request.getOperationName());

            // 直接抛出异常，让Spring GraphQL处理错误响应
            return Mono.error(new ServiceUnavailableException("Service temporarily unavailable due to database maintenance"));
        }

        // 原有的日志逻辑
        long startTime = System.currentTimeMillis();
        String query = request.getDocument();
        String operationName = request.getOperationName();
        Map<String, Object> variables = request.getVariables();

        logger.info("GraphQL Request - Operation: {}, Query: {}, Variables: {}",
                operationName, query, variables);

        return chain.next(request)
                .doOnNext(response -> {
                    long duration = System.currentTimeMillis() - startTime;
                    logger.info("GraphQL Response - Operation: {}, Duration: {}ms, Errors: {}",
                            operationName, duration, response.getErrors());
                })
                .doOnError(error -> {
                    long duration = System.currentTimeMillis() - startTime;
                    logger.error("GraphQL Error - Operation: {}, Duration: {}ms, Error: {}",
                            operationName, duration, error.getMessage());
                });
    }

    // 自定义异常类
    private static class ServiceUnavailableException extends RuntimeException {
        public ServiceUnavailableException(String message) {
            super(message);
        }
    }
}
